package com.imooc.coupon.service.impl;

import com.imooc.coupon.entity.CouponTemplate;
import com.imooc.coupon.service.IAsyncService;
import com.imooc.coupon.dao.CouponTemplateDao;
import com.imooc.coupon.exception.CouponException;
import com.imooc.coupon.service.IBuildTemplateService;
import com.imooc.coupon.vo.TemplateRequest;
import com.imooc.coupon.vo.TemplateRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author Administrator
 * @Date 2021/10/24 20:03
 * @Version 1.0
 */
@Slf4j
@Service
public class BuildTemplateServiceImpl implements IBuildTemplateService {

    @Autowired
    private IAsyncService asyncService;
    @Autowired
    private CouponTemplateDao templateDao;


    @Override
    public CouponTemplate buildTemplate(TemplateRequest request) throws CouponException {
        //参数合法化校验
        if (!request.validate()) {
            throw new CouponException("BuildTemplate Param is not Valid!");
        }
        if (null != templateDao.findByName(request.getName())) {
            throw new CouponException("Exists Same Name Template!");
        }
        CouponTemplate template = requestToTemplate(request);
        template = templateDao.save(template);
        //根据优惠劵异步服务，生成优惠劵码
        asyncService.asyncConstructCouponByTemplate(template);
        return template;
    }

    /**
     * 将TemplateRequest转换为CouponTemplate
     * @param request
     * @return
     */
    private CouponTemplate requestToTemplate(TemplateRequest request) {
        return new CouponTemplate(
                request.getName(),
                request.getLogo(),
                request.getDesc(),
                request.getCategory(),
                request.getProductLine(),
                request.getCount(),
                request.getUserId(),
                request.getTarget(),
                request.getRule());
    }
}
